import QtQuick 2.14
import QtQuick.Controls 2.14
import QtCharts 2.14

Item {
    id: chartContainer
    
    property string title: ""
    property string xAxisTitle: ""
    property string yAxisTitle: ""
    property alias chart: chartView
    property alias series: lineSeries
    
    implicitWidth: 400
    implicitHeight: 300
    
    Rectangle {
        anchors.fill: parent
        color: "white"
        border.color: "#E0E0E0"
        border.width: 1
        radius: 4
        
        Column {
            anchors.fill: parent
            anchors.margins: 10
            spacing: 5
            
            Text {
                text: title
                font.bold: true
                font.pixelSize: 16
                color: "#212121"
                anchors.horizontalCenter: parent.horizontalCenter
                visible: title !== ""
            }
            
            ChartView {
                id: chartView
                width: parent.width
                height: parent.height - (title !== "" ? 30 : 0)
                antialiasing: true
                backgroundColor: "transparent"
                
                margins.top: 0
                margins.bottom: 0
                margins.left: 0
                margins.right: 0
                
                LineSeries {
                    id: lineSeries
                    name: title
                    color: "#2196F3"
                    width: 2
                    
                    axisX: DateTimeAxis {
                        id: xAxis
                        titleText: xAxisTitle
                        format: "hh:mm"
                        tickCount: 5
                    }
                    
                    axisY: ValueAxis {
                        id: yAxis
                        titleText: yAxisTitle
                        min: 0
                        max: 100
                        tickCount: 6
                    }
                }
            }
        }
    }
    
    function addPoint(x, y) {
        lineSeries.append(x, y)
        
        // 保持最多50个数据点
        if (lineSeries.count > 50) {
            lineSeries.removePoints(0, lineSeries.count - 50)
        }
        
        // 自动调整Y轴范围
        var minY = Number.MAX_VALUE
        var maxY = Number.MIN_VALUE
        
        for (var i = 0; i < lineSeries.count; i++) {
            var point = lineSeries.at(i)
            minY = Math.min(minY, point.y)
            maxY = Math.max(maxY, point.y)
        }
        
        if (minY !== Number.MAX_VALUE && maxY !== Number.MIN_VALUE) {
            var range = maxY - minY
            yAxis.min = Math.max(0, minY - range * 0.1)
            yAxis.max = maxY + range * 0.1
        }
    }
    
    function clearData() {
        lineSeries.clear()
    }
    
    function setYAxisRange(min, max) {
        yAxis.min = min
        yAxis.max = max
    }
}